// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitTreesSha 获取项目文件和递归所有文件
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取文件内容
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitBlobsSha 获取文件Blob
// https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoContentsPath 新建文件
// https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
// https://gitee.com/api/v5/swagger#/deleteV5ReposOwnerRepoContentsPath 删除文件
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoBranches 获取所有分支
// https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoBranches 创建分支
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoCommits 仓库的所有提交(分页)
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoCommitsSha 仓库的某个提交
// inside: owner repo path content message branch
const git_url = 'https://gitee.com/api'
const header = {'Content-type': 'application/json;charset=UTF-8' }
const git_key = ['access_token','owner','repo','version']
const initext = 'ZGQK'
function Gitee() {
    /**
     * API文档 https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoContentsPath 新建文件
     * @param {*} path 
     * @param {*} content 
     * @param {*} message 
     * @param {*} branch 
     */
    this.create = function (path,content,message,branch) {
        console.log('开始创建新文件')
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
            let data = {
                'access_token':  access_token,
                'content': window.btoa(content),
                'message': message,
                'branch': branch,
            }
            fetch(url, {
                method: 'POST',
                body: JSON.stringify(data),
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '创建 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('创建' + path,resp)
            })
        })
    }

    /**
     * API文档：https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
     * @param {*} path 文件路径
     * @param {*} ref 分支、tag或commit。默认: 仓库的默认分支(通常是master)
     */
    this.getlist = function (path,ref,element,elenum) {
        console.log('获取新的文件列表')
        chrome.storage.local.get(git_key, function (result) {
            console.log('result', result)
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let version = result.version
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token + '&ref=' + ref
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('getlist', resp)
                if (resp['message'] != undefined) {
                    console.log('error',resp)
                } else {
                    resp.forEach((vds) => {
                        var op = document.createElement('option');
                        op.setAttribute('label', vds['name']);
                        op.setAttribute('value', vds['name']);
                        op.setAttribute('select', 'select')
                        element.appendChild(op);
                    })
                    elenum.innerText = resp.length
                }
            })
        })
    }

    /**
     * API文档：https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
     * @param {*} path 文件路径
     * @param {*} storage 
     */
    this.getTodo = function (path,storage) {
        console.log('更新本地书签信息')
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let version = result.version
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log(resp)
                let info = JSON.parse(decodeURIComponent(window.atob(resp['content'])))

                try {
                storage.set({
                    easyTodoStorage: info
                })
                } catch (e) {
                // do nothing
                } finally {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '更新本地书签',
                    message: '同步完成 '
                })
                }
            })
        })
    }

    // 获取指定文件内容
    /**
     * API文档：https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitBlobsSha 获取文件Blob
     * @param {*} sha 
     */
    this.get = function (sha) {
        console.log('获取制定文件信息', sha)
        chrome.bookmarks.getTree((re) => {
            chrome.storage.local.set({'repostatus': false}, () => {
                console.info("===删除本地书签===start")
                removeall(re)
                console.info("===删除本地书签===end")
                chrome.storage.local.get(git_key, function (result) {
                    let access_token = result.access_token
                    let owner = result.owner
                    let repo = result.repo
                    let url = git_url + '/v5/repos/' + owner + '/' + repo + '/commits/' + sha + '?access_token=' + access_token
                    console.log("远端地址：", url)
                    if (owner === '' || owner === undefined) {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('未配置认证信息 true')
                            console.log('reset repostatus === true')
                        })
                        return
                    }
                    fetch(url, {
                        method: 'GET',
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('error true',error)
                            console.log('reset repostatus === true')
                        })
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '获取文件Blob ' + sha,
                            message: error
                        })
                    })
                    .then((resp) => {
                        let url = git_url + '/v5/repos/' + owner + '/' + repo + '/git/blobs/' + resp['files'][0]['sha'] + '?access_token=' + access_token
                        fetch(url, {
                            method: 'GET',
                            headers: header
                        }).then(res => res.json())
                        .catch((error) => {
                            chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'img/icon.png',
                                title: '获取文件Blob ' + resp['files'][0]['sha'],
                                message: error
                            })
                        })
                        .then((resp2) => {
                            console.log("resp2==", resp2)
                            if (resp2['message'] == undefined) {
                                let info = JSON.parse(decodeURIComponent(window.atob(resp2['content'])))
                                try {
                                    addAll(info[0].children,'')
                                } catch (e) {
                                    console.log('error',e)
                                } finally {
                                    chrome.notifications.create(null, {
                                        type: 'basic',
                                        iconUrl: 'img/icon.png',
                                        title: '切换等待10秒',
                                        message: '请勿执行书签操作，否则手工完成同步操作'
                                    })
                                    setTimeout(() => {
                                    chrome.storage.local.set({ 'repostatus': true }, () => {
                                        chrome.notifications.create(null, {
                                        type: 'basic',
                                        iconUrl: 'img/icon.png',
                                        title: '更新本地书签完成',
                                        message: '启动书签自动同步功能'
                                        }) 
                                    })
                                    },10000);
                                }
                            } else {
                                console.log('error get ',resp2)
                            }
                        })
                    })
                })
            })
        })
    }

    // 获取指定文件内容
    /**
     * API文档：https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitBlobsSha 获取文件Blob
     * @param {*} sha 
     */
    this.getRemoteBookmarks = function (path) {
        console.log('获取指定路径文件信息', path)
        chrome.bookmarks.getTree((re) => {
            chrome.storage.local.set({'repostatus': false}, () => {
       
                chrome.storage.local.get(git_key, function (result) {
                    let access_token = result.access_token
                    let owner = result.owner
                    let repo = result.repo
                    let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
                    console.log("远端地址", url)
                    if (owner === '' || owner === undefined) {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('未配置认证信息 true')
                            console.log('reset repostatus === true')
                        })
                        return
                    }

                    fetch(url, {
                        method: 'GET',
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('error true',error)
                            console.log('reset repostatus === true')
                        })
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '获取文件Blob ' + path,
                            message: error
                        })
                    })
                    .then((resp) => {
                        console.log("git结果解析==", resp)
                        let info = JSON.parse(decodeURIComponent(window.atob(resp['content'])))
                        console.log("git结果解析:", info)
                        try {
                            console.info("开始添加书签", info[0].children)
                            addOrUpdate(info[0].children,'')
                        } catch (e) {
                            console.log('error',e)
                        } finally {
                            chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'img/icon.png',
                                title: '切换等待10秒',
                                message: '请勿执行书签操作，否则手工完成同步操作'
                            })
                            setTimeout(() => {
                            chrome.storage.local.set({ 'repostatus': true }, () => {
                                chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'img/icon.png',
                                title: '更新本地书签完成',
                                message: '启动书签自动同步功能'
                                }) 
                            })
                            },10000);
                        }
                    })
                })
            })
        })
    }


    this.getrecovery = function (path) {
        console.log('获取指定路径文件信息', path)
        chrome.bookmarks.getTree((re) => {
            chrome.storage.local.set({'repostatus': false}, () => {
                console.info("开始清除本地书签==start")
                removeall(re)
                console.info("开始清除本地书签==end")

                chrome.storage.local.get(git_key, function (result) {
                    let access_token = result.access_token
                    let owner = result.owner
                    let repo = result.repo
                    let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
                    console.log("远端地址", url)
                    if (owner === '' || owner === undefined) {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('未配置认证信息 true')
                            console.log('reset repostatus === true')
                        })
                        return
                    }

                    fetch(url, {
                        method: 'GET',
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('error true',error)
                            console.log('reset repostatus === true')
                        })
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '获取文件Blob ' + path,
                            message: error
                        })
                    })
                    .then((resp) => {
                        console.log("git结果解析==", resp)
                        let info = JSON.parse(decodeURIComponent(window.atob(resp['content'])))
                        console.log("git结果解析:", info)
                        try {
                            console.info("开始添加书签", info[0].children)
                            addAll(info[0].children,'')
                        } catch (e) {
                            console.log('error',e)
                        } finally {
                            chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'img/icon.png',
                                title: '切换等待10秒',
                                message: '请勿执行书签操作，否则手工完成同步操作'
                            })
                            setTimeout(() => {
                            chrome.storage.local.set({ 'repostatus': true }, () => {
                                chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'img/icon.png',
                                title: '更新本地书签完成',
                                message: '启动书签自动同步功能'
                                }) 
                            })
                            },10000);
                        }
                        // return window.atob(resp.content)
                    })
                })
            })
        })
    }

    /**
     * API文档： https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
     * @param {*} sha 
     * @param {*} message 
     */
    this.updateTagsSha = function (sha,message) {
        console.log('更新文件信息{}, {}', sha, message)
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            
            chrome.bookmarks.getTree((re) => {
                let data = {
                    "access_token": access_token,
                    "content": window.btoa(encodeURIComponent(JSON.stringify(re))),
                    "sha": sha,
                    "message": message
                }
                
                let put_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
                fetch(put_url, {
                    method: 'PUT',
                    body: JSON.stringify(data),
                    headers: header
                }).then(res => res.json())
                .catch((error) => {
                    chrome.notifications.create(null, {
                        type: 'basic',
                        iconUrl: 'img/icon.png',
                        title: '上传全量书签错误',
                        message: error
                    })
                })
                .then((resp) => {
                    console.log(resp)
                    chrome.notifications.create(null, {
                        type: 'basic',
                        iconUrl: 'img/icon.png',
                        title: '上传全量书签',
                        message: '成功'
                    })
                })
            })
        })
    }

    /**
     * API文档： https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
     * @param {*} path 
     * @param {*} message 
     * @param {*} ref 
     */
    this.updateTags = function (path,message,ref) {
        console.log('更新文件信息--{}--{}--{}', path, message, ref)
        let _this = this
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            
            // https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token + '&ref=' + ref
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('gitee get success' + JSON.stringify(resp), resp['sha'])
                if (resp['sha'] == undefined) {
                    _this.create(path,initext,'init','master')
                    _this.updateTags(path,message,ref)
                    return
                }
                chrome.bookmarks.getTree((re) => {
                    let data = {
                        "access_token": access_token,
                        "content": window.btoa(encodeURIComponent(JSON.stringify(re))),
                        "sha": resp['sha'],
                        "message": message
                    }
                    
                    let put_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
                    fetch(put_url, {
                        method: 'PUT',
                        body: JSON.stringify(data),
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签错误',
                            message: error
                        })
                    })
                    .then((resp) => {
                        console.log(resp)
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签',
                            message: '成功'
                        })
                    })
                })
            })
        })
    }

    /**
     * API文档： todo 远程同步TODOLIST
     * @param {*} path 
     * @param {*} message 
     * @param {*} ref 
     */
    this.updateTodo = function (path,message) {
        console.log('updateTodo:{}, {}', path, message)
        let _this = this
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            
            // https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('gitee get success' + JSON.stringify(resp), resp['sha'])
                if (resp['sha'] == undefined) {
                    _this.create(path,initext,'init','master')
                    _this.updateTodo(path,message)
                    return
                }
                chrome.bookmarks.getTree((re) => {
                    let data = {
                        "access_token": access_token,
                        "content": window.btoa(encodeURIComponent(JSON.stringify(re))),
                        "sha": resp['sha'],
                        "message": message
                    }
                    
                    // https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
                    let put_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
                    fetch(put_url, {
                        method: 'PUT',
                        body: JSON.stringify(data),
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签错误',
                            message: error
                        })
                    })
                    .then((resp) => {
                        console.log(resp)
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签',
                            message: '成功'
                        })
                    })
                })
            })
        })
    }

    /**
     * API文档：https://gitee.com/api/v5/swagger#/deleteV5ReposOwnerRepoContentsPath 删除文件
     * @param {*} path 
     * @param {*} message 
     */
    this.delete = function (path,message) {
        console.log('delete:{}, {}', path, message)

        chrome.storage.local.get(git_key, function (result) {
            let _this = this
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
            console.info('delete====url===', url)
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                var sha = '';
                console.log('======gitee=====delete====', resp)
                if (resp['sha'] != null) {
                    console.log('======gitee=====delete=----', resp['sha'])
                    // 如果是目录类型的，sha 会放在数组中
                    sha = resp['sha']
                } else {
                    console.log('======gitee=====delete=----', resp[0]['sha'])
                    sha = resp[0]['sha']
                }
                let del_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token + '&sha=' + sha + '&message=' + message 
                fetch(del_url, {
                    method: 'DELETE',
                    headers: header
                }).then(res => res.json())
                .catch((error) => {
                    console.error('Error:', error) 
                })
                .then((resp) => {
                    console.log('github delete success' + JSON.stringify(resp))
                    chrome.notifications.create(null, {
                        type: 'basic',
                        iconUrl: 'img/icon.png',
                        title: '书签删除',
                        message: '远程书签 ' + path + ' 删除完毕！'
                    })
                })
            })
        })
    }
    
    /**
     * API文档：https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoCommits 仓库的所有提交(分页)
     * @param {*} path 包含该文件的提交
     * @param {*} page 当前的页码
     * @param {*} per_page 每页的数量，最大为 100
     */
    this.getallcommit = function (path,page,per_page,element) {
        console.log('getallcommit:{}, {},{},{}', path, page, per_page, element)
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/commits?access_token=' + access_token + '&path=' + path + '&page=' + page + '&per_page=' + per_page
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '仓库的所有提交 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                // console.log(resp)
                // return resp
                resp.forEach((vds) => {
                    var op = document.createElement('option');
                    op.setAttribute('label', vds['commit']['message']);
                    op.setAttribute('value', vds['sha']);
                    op.setAttribute('select', 'select')
                    element.appendChild(op);
                })
            })
        })
    }

    /**
     * 本地保存reponame
     * @param {*} name
     */
    this.saveName = function (name) {
        console.log('saveName--', name)
        chrome.storage.local.set({'reponame': name}, () => {
            console.log('set repo name ok')
        })
    }
}
